package date0702;

/* 若文件中有若干个Object对象，你用ObjectInputStream中的readObject()去读，何时判读到结尾？
* 方法之一：（常用的方法）将若干个对象（数量不定）都装入一个容器中（如：ArrayList之类），
* 然后将容器这一个对象写入就行了。读取时，只要读取一个对象（即容器对象）就行了;
* 方法二：（若不想用容器），则由于数量不定，正是用EOFException来判断结束。
* */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;


public class StudentDaoFile implements StudentDao {
	List<Student> list2=new ArrayList<Student>();

	@Override
	public boolean save(Student s) throws IOException {
		// TODO Auto-generated method stub
		list2.add(s);
		Path f=Path.of("student.dat");
		//File f=new File("student.dat");
		//OutputStream out=new FileOutputStream(f, true);
		if (Files.notExists(f)) {
			Files.createFile(f);
		}
		OutputStream out = Files.newOutputStream(f, StandardOpenOption.WRITE,StandardOpenOption.CREATE);
		ObjectOutput oo = new ObjectOutputStream(out);
		oo.writeObject(list2);
		oo.close();
		out.close();
		return true;
	}

	@Override
	public Student find(Integer id) throws FileNotFoundException, IOException, ClassNotFoundException {
		// TODO Auto-generated method stub
		Student h=new Student();
		File f=new File("student.dat");
		InputStream in = new FileInputStream( f );
		ObjectInput oi = new ObjectInputStream(in);
		@SuppressWarnings("unchecked")
		List<Student> list=(List<Student>)oi.readObject();
		for(int i=0;i<list.size();i++) {
			if(list.get(i).getId().equals(id)) {
				h=list.get(i);
			}
		}
		oi.close();
		in.close();
		return h;
		/*try {
			while(true) {
				Object o=oi.readObject();
				Student h = (Student) o ;
				list.add(h);
			}
		}catch (EOFException  e) {
			// TODO: handle exception
		}finally {
			oi.close();
			in.close();
			
		}
				for(Student a:list) {
					if(a.getId().equals(id))
						return a;
				}
			return null;*/
	}
	

}
